<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 头部区域 -->
      <PageTools>
        <template slot="slot-left">
          <span>共 {{ total }} 条记录</span>
        </template>
        <template slot="slot-right">
          <el-button type="danger" size="small" @click="$router.push('/excel')">导入excel</el-button>
          <el-button type="success" size="small" @click="exportExcel">导出excel</el-button>
          <el-button type="primary" size="small" @click="dialogVisible=true">新增员工</el-button>
        </template>
      </PageTools>

      <!-- 主体区域 -->
      <el-card class="box-card" style="margin-top:20px">
        <!-- 主体表格 -->
        <el-table
          :data="employeeList"
          border
          :default-sort="{prop: 'username', order: 'descending'}"
        >
          <el-table-column type="index" label="序号" />
          <el-table-column prop="username" label="姓名" />

          <el-table-column label="头像">
            <template slot-scope="scope">
              <image-holder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" />
          <el-table-column prop="workNumber" label="工号" />
          <el-table-column :formatter="formatter" prop="formOfEmployment" label="聘用形式" />
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column sortable label="入职时间">
            <template slot-scope="scope">
              <span>{{ scope.row.timeOfEntry |formatTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="转正时间">
            <template slot-scope="scope">
              <span>{{ scope.row.correctionTime |formatTime }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="timeOfEntry" label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmployeesBtn(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          text-align:
          center
          :current-page="query.page"
          :page-sizes="[10, 15, 20, 25]"
          :page-size="query.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <!-- 添加员工弹框 -->
        <el-dialog
          title="添加员工"
          :visible.sync="dialogVisible"
          width="50%"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          @close="dialogClose"
        >
          <empDialog ref="form" @close="closeFn" />
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
// 接口
import { getEmployeeListAPI, delEmployeeAPI } from '@/api/employees'
// 枚举
import EmployeeEnum from '@/constant/employees'
// 添加组件
import empDialog from './empDialog.vue'
// 时间处理插件
import dayjs from 'dayjs'
export default {
  name: 'Employees',
  components: {
    empDialog
  },
  filters: {
    formatTime(time) {
      return dayjs(time).format('YYYY-MM-DD')
    }
  },
  data() {
    return {
      query: {
        page: 1, // 页码
        size: 10 // 每页条数
      },
      total: 0, // 数据总条数
      employeeList: [], // 员工列表
      hireType: EmployeeEnum.hireType, // 聘用形式枚举
      dialogVisible: false // 添加员工弹框状态
    }
  },
  created() {
    //   调用获取员工列表的方法
    this.getEmployeeListFn()
  },
  methods: {
    // 每页条数
    handleSizeChange(newPageSize) {
      this.query.size = newPageSize
      this.getEmployeeListFn()
    },
    // 当前页码
    handleCurrentChange(page) {
      this.query.page = page
      this.getEmployeeListFn()
    },

    // 删除按钮
    async delEmployeesBtn(id) {
      const res = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (res === 'cancel') return this.$message('已取消删除')
      await delEmployeeAPI(id)
      // 分页异常处理
      if (this.employeeList.length <= 1) {
        this.query.page--
        if (this.query.page <= 0) {
          this.query.page = 0
        }
      }
      this.getEmployeeListFn()
    },

    // 聘用形式内容格式化
    formatter(row, column, cellValue, index) {
      const obj = this.hireType.find(item => +item.id === +cellValue)
      return obj ? obj.value : '未知'
    },

    // Dialog关闭添加弹框
    dialogClose() {
      // 调用子组件的方法,置空表单
      this.$refs.form.resetForm()
    },

    // 子组件点击添加或取消按钮后关闭弹窗
    closeFn(state) {
      console.log(state)
      if (state === '添加') {
        this.getEmployeeListFn()
        this.dialogVisible = false
      } else {
        this.dialogVisible = false
      }
    },

    // 导出excel
    async  exportExcel() {
      const res = await getEmployeeListAPI(this.query)
      console.log(res.data.rows)
      const { header, data } = this.transData(res.data.rows)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: header,
          data: data,
          filename: '员工列表',
          autoWidth: true,
          bookType: 'xlsx'
        })
        this.downloadLoading = false
      })
    },
    // 数据处理
    transData(rows) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const headerlist = Object.keys(rows[0])
      const header = headerlist.map(item => {
        return map[item]
      })
      //   return header
      const data = rows.map(item => {
        return Object.values(item)
      })

      return { header, data }
    },
    // 获取员工列表方法
    async getEmployeeListFn() {
      const res = await getEmployeeListAPI(this.query)
      this.employeeList = res.data.rows
      this.total = res.data.total
    }

  }

}
</script>

<style lang="scss" scoped></style>
